/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.gadgets.discussions.client;

import java.util.HashMap;

import com.gadglet.client.gwt.GadgetNativeUtils;
import com.gadglet.client.gwt.GadgetUtils;
import com.gadglet.client.gwt.core.GadgletQuery;
import com.gadglet.client.gwt.core.GadgletRequest;
import com.gadglet.client.gwt.core.GadgletResponse;
import com.gadglet.client.gwt.ui.ActionLabel;
import com.gadglet.client.gwt.ui.ContentText;
import com.gadglet.client.gwt.ui.DebugDialogBox;
import com.gadglet.client.gwt.ui.HomeViewMainPanel;
import com.gadglet.client.gwt.ui.SimpleDialogBox;
import com.gadglet.client.gwt.ui.UIUtils;
import com.gadglet.gadgets.discussions.shared.Params;
import com.gadglet.params.ProfileFields;
import com.gadglet.params.ReqActionTypes;
import com.gadglet.params.ReqTypes;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.gadgets.client.ContentSection;
import com.google.gwt.gadgets.client.Gadget.ContentType;
import com.google.gwt.gadgets.client.Gadget.InjectContent;
import com.google.gwt.gadgets.client.PreferencesFeature;
import com.google.gwt.gadgets.client.PreferencesProvider;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;

@InjectContent(files = "home.html")
@ContentType(type = "html", views = { "home", "default" })
public class DiscussionsHomeView extends ContentSection<DiscussionsGadget> {

	private DebugDialogBox debug = null;
	/**
	 *  Query object use to create a request for personal notes
	 *  The definition "ReqTypes.BIZLET_SIGNED" will create requests to the
	 *  Bizlets Servlet domainSignedRequest
	 *  @see com.gadglet.servlets.domainSignedRequest
	 */
	final GadgletQuery viewDiscussionsQry = new GadgletQuery(ReqTypes.BIZLET_SIGNED);
	
	/**
	 * Request object used to send and a request to the gadget server
	 * and process the results
	 */
	final ViewBookMarks viewDiscussionsRequest = new ViewBookMarks(
			viewDiscussionsQry);


	/**
	 * Query object used to build "add",  and "delete" requests
	 * The definition "ReqTypes.BIZLET_SIGNED" will create requests to the
	 *  Bizlets Servlet 
	 */
	final GadgletQuery changeDiscussionQry = new GadgletQuery(
			ReqTypes.BIZLET_SIGNED);
	
	final GadgletRequest changeDiscussionRequest = new ChangePersonalNotes(
			changeDiscussionQry);

	final Grid results = new Grid();
	protected final HorizontalPanel paging = new HorizontalPanel();

	final Button prevButton = new Button();
	final Button nextButton = new Button();
	final PreferencesFeature  prefsUtils = PreferencesProvider.get();
	final SimpleDialogBox serverMessage = SimpleDialogBox
			.getMesseageDialogBox();

	@Override
	public void init(DiscussionsGadget gadget) {

		debug = DebugDialogBox.getErrorNotifier();

		prevButton.setText(prefsUtils.getMsg("gadgetLabelPrevious"));
		nextButton.setText(prefsUtils.getMsg("gadgetLabelNext"));
		
		try {
			GadgetNativeUtils.setTitle(prefsUtils.getMsg("gadgetTitleDiscussions"));
		} catch (Exception e) {

		}
		

		final HomeViewMainPanel mainPanel = new HomeViewMainPanel();

		final HorizontalPanel addItemPanel = new HorizontalPanel();
		final DisclosurePanel addDisclosurePanel = new DisclosurePanel();
		
		
		final VerticalPanel bookMark = new VerticalPanel();
		
		final TextArea DiscussionText = new TextArea();
		DiscussionText.setWidth("200px");
	
		
		bookMark.add(DiscussionText);
	

		final Button saveButton = new Button(
				prefsUtils.getMsg("gadgetLabelSave"));


		addItemPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_BOTTOM);
		addItemPanel.add(bookMark);
		
		//addItemPanel.add(new HTML("&nbsp;"));
		//addItemPanel.add(bookMarkType);
	
		addItemPanel.add(new HTML("&nbsp;"));
		addItemPanel.add(saveButton);

		addDisclosurePanel.add(addItemPanel);
		
		ActionLabel add = new ActionLabel(prefsUtils.getMsg("gadgetLabelAdd"));
		add.setTitle(prefsUtils.getMsg("gadgetLabelAdd"));
		add.setStyleName("gadglet-ActionLabel");
		
		addDisclosurePanel.setHeader(add);

		mainPanel.add(addDisclosurePanel);

		mainPanel.add(results);

		RootPanel.get().add(mainPanel.getGadgetPanel());

		saveButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				changeDiscussionQry.setRequestAction(ReqActionTypes.ADD);
				changeDiscussionQry.clearParamList();
				
				
				changeDiscussionQry.addParam(Params.DISCUSSION_TEXT.getParamName(),
						DiscussionText.getValue());
			
				changeDiscussionRequest.makeRequest();
				DiscussionText.setValue("");
			

			}
		});

		viewDiscussionsQry.setRequestAction(ReqActionTypes.VIEW);
		
		viewDiscussionsQry.setStartItemsFrom(0);
		viewDiscussionsQry.setItemsNum(15);
		viewDiscussionsRequest.makeRequest();

		prevButton.setVisible(false);
		prevButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				viewDiscussionsQry.setStartItemsFrom(viewDiscussionsQry
						.getStartFrom() - viewDiscussionsQry.getItemNum());
				viewDiscussionsRequest.makeRequest();

			}

		});
		paging.add(prevButton);

		nextButton.setVisible(false);
		nextButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				viewDiscussionsQry.setStartItemsFrom(viewDiscussionsQry
						.getStartFrom() + viewDiscussionsQry.getItemNum());
				viewDiscussionsRequest.makeRequest();

			}

		});
		paging.add(nextButton);

	}

	public class ViewBookMarks extends GadgletRequest {
		GadgletResponse jResponse;

		ViewBookMarks(GadgletQuery req) {
			super(req);

		}

		@Override
		protected void processResults(GadgletResponse data) {
			jResponse = data;

			if (jResponse.isSuccessful()) {

				results.resize(1, 4);
				results.clear();
				int index;
				
				
			
				for (index = 0; index < jResponse.getRootItemsNum(); index++) {

				
					
					ContentText text = new ContentText(data.getStringItemValue(
							Params.DISCUSSION_TEXT.getParamName(), index));
					
					final String discussionId = jResponse.getItemKeyValue(index);
					
					results.setWidget(
							index,
							0,text);
					
					final String title = data.getStringItemValue(
							Params.DISCUSSION_TEXT.getParamName(), index);
					
					final ActionLabel viewLabel = new ActionLabel(prefsUtils.getMsg("gadgetLabelView"));

					viewLabel.addClickHandler(new ClickHandler() {
						@Override
						public void onClick(ClickEvent event) {
							
							
							HashMap <String,String> params = new HashMap <String,String> ();
							params.put(Params.DISCUSSION_ID.getParamName(), discussionId);
							
							params.put(Params.DISCUSSION_TEXT.getParamName(), title);
							
							GadgetNativeUtils.requestNavigateToCanvas(GadgetUtils.createJsonParamList(params));
							
							
							
						}

					});
					
					results.setWidget(
							index,
							1,viewLabel);
					

					if (!data.isDeletePermitted(index)) {

						String nick = data.getStringItemValue(ProfileFields.PROFILE_NICKNAME.getParamName(),index);
						
						HorizontalPanel profile = new HorizontalPanel();
						if(nick!=null){
							profile.add(new HTML(prefsUtils.getMsg("gadgetLabelSharedBy")+":"));
							profile.add(UIUtils.getSpace());
							profile.add(new Label(nick));

						}
											
						results.setWidget(index, 2, profile);
						
					}
					results.resize(index + 3, 4);

				}

				if (viewDiscussionsQry.getStartFrom() > 0)
					prevButton.setVisible(true);
				else
					prevButton.setVisible(false);

				if (jResponse.hasMoreItems())
					nextButton.setVisible(true);
				else
					nextButton.setVisible(false);

				results.setWidget(index, 0, paging);

			}

			else {
				debug.showError(1, jResponse.getError());
			}

		}
	}

	public class ChangePersonalNotes extends GadgletRequest {
		ChangePersonalNotes(GadgletQuery req) {
			super(req);
		}

		@Override
		protected void processResults(GadgletResponse data) {
			GadgletResponse jResponse = data;

			if (jResponse.isSuccessful()) {
				// reffresh
				viewDiscussionsRequest.makeRequest();
			} else {

				serverMessage
						.showError(prefsUtils.getMsg(jResponse.getError()));
			}

		}
	}

}
